<?php
namespace app\demo\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
class Cate extends Controller{
    public function one(){
        $res=Db::table('category')->select();
        $data=$this->getTree($res);
        $this->assign('data',$data);
        return view('cat_list');
    }

    //分类添加
    public function plus(){
        $data=Request::instance()->param();
        $res=Db::table('category')->insert($data);
        if($res){
            $this->success('添加成功','one');
        }else{
            $this->error('添加失败');
        }
    }
    //分类下拉菜单展示
    public function adds(){
        $res=Db::table('category')->select();
        $data=$this->getTree($res);
        $this->assign('data',$data);
        return view('cat_add');
    }
    //使用递归循环出菜单
    public function getTree($data,$leve=1,$pid=0){
        static $arr=array();
       foreach($data as $k=>$v){
           if($v['parent_id']==$pid){
               $v['level']=$leve;
               $arr[]=$v;
               unset($data[$k]);
               $this->getTree($data,$leve+1,$v['cat_id']);
           }
       }
        return $arr;
    }
    //分类修改
    public function change(){
        $catid=input('catid');
        $data=Db::table('category')->find($catid);//找到该条数据
        $res=Db::table('category')->select();//找到菜单栏
        $a=$this->getTree($res);
        $this->assign('data',$data);
        $this->assign('res',$a);
        return view('cat_edit');
    }
    public function changed(){
        $data=Request::instance()->param();
        $res=Db::table('category')->update($data);
        if($res){
            $this->success('修改成功','one');
        }else{
            $this->error('修改失败');
        }
    }
}